#include <iostream>
#include <cerrno>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <string.h>
#include <unistd.h>

int main(int args, char *argv[])
{
    // 1.创建socket套接字文件
    int sock = socket(AF_INET, SOCK_STREAM, 0);
    if (sock < 0)
    {
        std::cout << "socket create error" << errno << std::endl;
        return 1;
    }

    struct sockaddr_in sever;
    memset(&sever, 0, sizeof(sever));
    sever.sin_family = AF_INET;
    sever.sin_addr.s_addr = inet_addr(argv[1]);
    sever.sin_port = htons(atoi(argv[2]));
    // 2.client不需要绑定IP和端口号，所以直接建立链接即可。
    if (connect(sock, (struct sockaddr *)&sever, sizeof(sever)) < 0)
    {
        std::cout << "connect failed" << std::endl;
        return 2;
    }

    // 3.建立连接成功了，使用服务
    while (1)
    {

        std::cout << "#请输入： ";

        char buffer[1024];
        memset(buffer, 0, sizeof(buffer));
        fgets(buffer, sizeof(buffer - 1), stdin);

        write(sock, buffer, sizeof(buffer) - 1);
        size_t s = read(sock, buffer, sizeof(buffer) - 1);

        if (s > 0)
        {
            buffer[s] = 0;
            std::cout << " sever echo" << buffer << std::endl;
        }
    }

    return 0;
}